package com.qian2.pricesharingapplication;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;
import com.google.zxing.client.android.CaptureActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class barcode_Scanner extends Activity{
	private static String url_search_uid = "http://wwwfyp.cse.ust.hk:7117/search_product.php";
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "product";
	private static final String TAG_UID = "uid";
	JSONArray products = null;
	JSONParser jParser = new JSONParser();
	String scanContent ="";
	String findUid="";
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	//	public barcode_Scanner() {
	//		// TODO Auto-generated constructor stub
	//	}
	
	public boolean isOnline() {
		ConnectivityManager cm =
				(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_barcode_scanner);
		ImageButton barcode_button= (ImageButton) this.findViewById(R.id.ScannerButton);
		barcode_button.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(barcode_Scanner.this, CaptureActivity.class);
				intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
				startActivityForResult(intent, 0);
				// See more at: http://techiedreams.com/android-zxing-barcode-scanner-integration/#sthash.YO6zAgBL.dpuf	
			}

		});
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		//if (requestCode == SCANNER_REQUEST_CODE) {
			// Handle scan intent
			if (resultCode == Activity.RESULT_OK) {
				// Handle successful scan
				scanContent="";
				String contents = intent.getStringExtra("SCAN_RESULT");
				TextView barcode_result=(TextView) this.findViewById(R.id.barcode_result);
				barcode_result.setText(contents);
				intent.getStringExtra("SCAN_RESULT_FORMAT");
				intent.getByteArrayExtra("SCAN_RESULT_BYTES");
				int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
				intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");

				scanContent=contents;
				new GetUid().execute();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				// Handle cancel
			}
	//	} else {
	//		// Handle other intents
	//	}

	}


	class GetUid extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}
		/**
		 * Getting product details in background thread
		 * */
		protected String doInBackground(String... args) {

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();			
			params.add(new BasicNameValuePair("upc", scanContent));
			JSONObject json=null;
			json = jParser.makeHttpRequest(url_search_uid, "GET", params);
			Log.d("Search Response Json: ", json.toString());
			//System.out.println(json);
			try {
				// Checking for SUCCESS TAG
				int success =0;
				if (isOnline() && json!=null){
					success = json.getInt(TAG_SUCCESS);
					if (success == 1 ) {
						// products found
						// Getting Array of Products
						products = json.getJSONArray(TAG_PRODUCTS);
						

						// looping through All Products
						for (int i = 0; i < products.length(); i++) {
							JSONObject c = products.getJSONObject(i);

							// Storing each json item in variable
							findUid = c.getString(TAG_UID);
						

							
							
						}
					}else{
						findUid ="Not_Found";
						scanContent="";
					}
				} else if (!isOnline()){
					// Storing each json item in variable
					 findUid = "No_network";
					//String description = c.getString(TAG_description);

				} 				
				else {
					// Storing each json item in variable
					findUid = "Server_error";
					//String description = c.getString(TAG_description);

					// creating new HashMap
									}
			} catch (JSONException e) {
				e.printStackTrace();
				
			}
			
			

			
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			//pDialog.dismiss();
			if (!findUid.equals("Server_error") && !findUid.equals("No_network")){
				// Starting new intent
				if(!findUid.equals("Not_Found") && !findUid.isEmpty()){
				Intent in = new Intent(getApplicationContext(),
						ProductPage.class);
				// sending uid to next activity
				
				in.putExtra(TAG_UID, findUid);
				
				startActivityForResult(in, 110);
				}
				else{
					Toast toast = Toast.makeText(getApplicationContext(), 
							"No products found!", Toast.LENGTH_SHORT);
					toast.show();
				}
			}

		}
	}
	
}
